import store from '@/store';
import axios from 'axios';
import { Message } from 'element-ui';
import Router from '@/router/index';

// 创建一个axios实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, 
  withCredentials: false, 
  timeout: 60*1000,
  headers: {'Content-Type':'application/json'},
  //是否返回其它状态码
  validateStatus:function(status){
    return status >= 200 && status <= 500
  },
});

// 请求拦截器
service.interceptors.request.use(
  config=>{
    try {
      let token = store.getters.token
      config.headers['X-Access-Token'] = `${token}`;
    } catch(error){console.log(error)}
    return config
  },
  error => {
    return Promise.reject(error);
  }
)

// 响应拦截器
service.interceptors.response.use(
  response=>{
    const res = response.data;
    let status = response.status
    //用户信息失效，重定向登录页
    // if(status === 500 && res.code == 401){
    //   clearCookie()
    //   window.location.href = `${process.env.VUE_APP_ZDB_URL}/user/login?redirect=${window.location.origin}`
    //   return
    // }
    //返回错误
    if(status !== 200){
      Message({
        message: response.data.msg,
        type: 'error'
      })
      return Promise.reject(new Error(response.message))
    }
    return res
  },
  error=>{
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    });
    return Promise.reject(error);
  }
)

//清空cookie
function clearCookie() {
  var keys = document.cookie.match(/[^ =;]+(?=\=)/g);
  if (keys) {
    for (var i = keys.length; i--;) {
      document.cookie = keys[i] + '=0;path=/;expires=' + new Date(0).toUTCString();//清除当前域名下的,例如：m.kevis.com
      document.cookie = keys[i] + '=0;path=/;domain=' + document.domain + ';expires=' + new Date(0).toUTCString();//清除当前域名下的，例如 .m.kevis.com
      document.cookie = keys[i] + '=0;path=/;domain=kevis.com;expires=' + new Date(0).toUTCString();//清除一级域名下的或指定的，例如 .kevis.com
    }
  }
  console.log('已清除');
}


export default service;